import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:hari_curly/src/model/device_model.dart';
import 'package:loading_indicator/loading_indicator.dart';

import '../../../common/style.dart';
import '../../../components/layout.dart';

const String serviceUUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
const String charWriteUUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
const String charNotifyUUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";

class DevicePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState()  => _DevicePageState ();
}

class _DevicePageState  extends State<DevicePage>{

  List<DeviceModel>  _devices = [];
  _showLoadingDialog(BuildContext context) {
    FlutterBluePlus.startScan(
        withServices:[Guid(serviceUUID)], // match any of the specified services
        withNames:["Bluno"], // *or* any of the specified names
        timeout: Duration(seconds:15));
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            // 背景透明
              backgroundColor: Colors.transparent,
              content: Container(
                // 背景透明
                color: Colors.transparent,
                width: 200,
                height: 100,
                child: Column(
                  children: [
                    Container(
                      width: 50,
                      height: 50,
                      child: LoadingIndicator(
                        indicatorType: Indicator.values[21],
                        strokeWidth: 1,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('device_connect_tip'.tr()),
                  ],
                ),
              ));
        });
    Future.delayed(Duration(seconds: 5), () {
      Navigator.of(context).pop();
      Fluttertoast.showToast(
          msg: "device_connect_error".tr(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black45,
          textColor: Colors.white,
          fontSize: 16.0);
    });
  }

  @override
  void initState() {
    super.initState();
    _initData();
  }
  _initData() async {
  List<DeviceModel> devices = await DeviceModel.getAll();
  setState(() {
    _devices = devices;
  });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: pageBgColor,
      appBar: AppBarUnit(
        title: Text("device_page_title".tr()),
        back: true,
        onPressed: () {
          context.pop();
        },
      ),
      // 更具 底部导航栏的索引值，显示不同的页面
      body: Column(children: [
        Container(
            width: MediaQuery.of(context).size.width,
            constraints: BoxConstraints(minHeight: 40),
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 0),
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
              child: Card(
                  color: unitBgColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: InkWell(
                    borderRadius: BorderRadius.circular(10.0),
                    child: Container(
                      padding: EdgeInsets.fromLTRB(0, 0, 18, 0),
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.topLeft,
                            padding: EdgeInsets.all(8),
                            child: Text("device_sub_title".tr()),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      context.push("/device/scan");
                    },
                  )

              ),
            )),
        ..._devices.map((device) {
          return   Container(
              width: MediaQuery.of(context).size.width,
              constraints: BoxConstraints(minHeight: 40),
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
                child: Card(
                    color: unitBgColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    child: InkWell(
                      borderRadius: BorderRadius.circular(10.0),
                      child: Container(
                        padding: EdgeInsets.all(12),
                        child: Row(
                          children: [
                            Container(
                              //圆角
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10.0),
                                color: pageBgColor,
                              ),
                              alignment: Alignment.topLeft,
                              padding: EdgeInsets.all(20),
                              margin: EdgeInsets.fromLTRB(0, 0, 12, 0),
                              child: Icon(
                                Icons.bluetooth,
                                color: Colors.white,
                                size: 32,
                              ),
                            ),
                            Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      device.name!.toUpperCase(),
                                      style: TextStyle(
                                          fontSize: 14, fontWeight: FontWeight.bold),
                                    ),
                                    Text(
                                      device.id!,
                                      style:
                                      TextStyle(fontSize: 12, color: Colors.grey),
                                    ),
                                  ],
                                )),
                            Container(
                                child: Container(
                                    alignment: Alignment.centerRight,
                                    child: Row(
                                      children: [
                                        Text(device.status!),
                                        device.status=='1'?
                                        Text("device_connect".tr(),
                                            style: TextStyle(
                                                fontSize: 12,
                                                fontWeight: FontWeight.bold,
                                                color: Colors.green)): Text("device_disconnect".tr(),
                                            style: TextStyle(
                                                fontSize: 12,
                                                fontWeight: FontWeight.bold,
                                                color: Colors.red)),
                                        Icon(
                                          Icons.arrow_forward_ios,
                                          color: Colors.grey,
                                          size: 18,
                                        ),
                                      ],
                                    ))),
                          ],
                        ),
                      ),
                      onTap: () {
                        // 弹出加载中5s后自动关闭
                        _showLoadingDialog(context);
                      },
                    )),
              ));
        })

      ]),
    );
  }
}
